package com.github.tvbox.osc.util;

import static com.bumptech.glide.load.resource.bitmap.VideoDecoder.FRAME_OPTION;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import io.github.source.util.UrlUtil;
import me.jessyan.autosize.utils.AutoSizeUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.github.catvod.utils.Json;
import com.github.tvbox.osc.R;
import com.github.tvbox.osc.base.App;
import com.google.common.net.HttpHeaders;

import java.util.Map;

public class ImgUtil {
    public static void load(String url, ImageView view) {
        load(url, view, 10);
    }

    public static void load(String url, ImageView view, ImageView.ScaleType scaleType) {
        load(url, view, 10, scaleType);
    }

    public static void load(String url, ImageView view, int roundingRadius, ImageView.ScaleType scaleType) {
        view.setScaleType(ImageView.ScaleType.FIT_CENTER);
        if (TextUtils.isEmpty(url)) {
            view.setImageResource(R.drawable.img_loading_placeholder);
        } else {
            if (roundingRadius == 0) roundingRadius = 1;
            RequestOptions requestOptions = new RequestOptions()
                .format(DecodeFormat.PREFER_RGB_565)
                .diskCacheStrategy(getDiskCacheStrategy(4))
                .dontAnimate()
                .transform(
            new RoundedCorners(roundingRadius));
            Glide.with(App.getInstance())
                .asBitmap()
                .load(getUrl(url))
                .error(R.drawable.img_loading_placeholder)
                .placeholder(R.drawable.img_loading_placeholder)
                .listener(getListener(view, scaleType))
                .apply(requestOptions)
                .into(view);
        }
    }
   static RequestOptions requestOptions = new RequestOptions()
            .format(DecodeFormat.PREFER_RGB_565)
            .diskCacheStrategy(getDiskCacheStrategy(4))
            .dontAnimate()
            .transform(
                    new CenterCrop());

    public static void load(String url, ImageView view, int roundingRadius) {
        view.setScaleType(ImageView.ScaleType.CENTER);
        if (TextUtils.isEmpty(url)) {
            view.setImageResource(R.drawable.img_loading_placeholder);
        } else {
            if (roundingRadius == 0) roundingRadius = 1;
            Glide.with(view)
                    .load(getUrl(url))
                    .error(R.drawable.img_loading_placeholder)
                    .placeholder(R.drawable.img_loading_placeholder)
                    .apply(requestOptions)
                    .into(view);
        }
    }

    /*
     * 使用Glide方式获取视频某一帧
     * @param uri 视频地址
     * @param imageView 设置image
     * @param frameTimeMicros 获取某一时间帧.
     */
    public static void loadVideoScreenshot(String uri, ImageView imageView, long frameTimeMicros) {
        RequestOptions requestOptions = RequestOptions.frameOf(frameTimeMicros * 1000)
                .set(FRAME_OPTION, MediaMetadataRetriever.OPTION_CLOSEST)
                .transform(
                        new CenterCrop(),
                        new RoundedCorners(10));
        Glide.with(App.getInstance())
                .load(uri)
                .skipMemoryCache(true)
                .apply(requestOptions)
                .into(imageView);
    }

    public static String getDiskCacheStrategyName(int index) {
        String[] names = new String[] {
                "[NONE] 关闭", "[RESOURCE] 转换图片", "[DATA] 原始图片 ", "[ALL] 原始图片和转换图片", "[AUTOMATIC] 自动"
        };
        return names[index];
    }

    public static DiskCacheStrategy getDiskCacheStrategy(int index) {
        switch (index) {
            case 1:
                return DiskCacheStrategy.RESOURCE;
            case 2:
                return DiskCacheStrategy.DATA;
            case 3:
                return DiskCacheStrategy.ALL;
            case 4:
                return DiskCacheStrategy.AUTOMATIC;
            default:
                return DiskCacheStrategy.NONE;
        }
    }
    public static Object getUrl(String url) {
        if (url.startsWith("data:")) return url;

        url = UrlUtil.convert(url);
        String param = null;
        LazyHeaders.Builder builder = new LazyHeaders.Builder();
        if (url.contains("@Headers=")) addHeader(builder, param = url.split("@Headers=")[1].split("@")[0]);
        if (url.contains("@Cookie=")) builder.addHeader(HttpHeaders.COOKIE, param = url.split("@Cookie=")[1].split("@")[0]);
        if (url.contains("@Referer=")) builder.addHeader(HttpHeaders.REFERER, param = url.split("@Referer=")[1].split("@")[0]);
        if (url.contains("@User-Agent=")) builder.addHeader(HttpHeaders.USER_AGENT, param = url.split("@User-Agent=")[1].split("@")[0]);

        url = param == null ? url : url.split("@")[0];
        return TextUtils.isEmpty(url) ? null : new GlideUrl(url, builder.build());
    }
    private static void addHeader(LazyHeaders.Builder builder, String header) {
        Map<String, String> map = Json.toMap(Json.parse(header));
        for (Map.Entry<String, String> entry : map.entrySet()) builder.addHeader(UrlUtil.fixHeader(entry.getKey()), entry.getValue());
    }

    private static RequestListener < Bitmap > getListener(ImageView view, ImageView.ScaleType scaleType) {
        return new RequestListener < Bitmap > () {@Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target < Bitmap > target, boolean isFirstResource) {
            view.setScaleType(scaleType);
            view.setImageResource(R.drawable.img_loading_placeholder);
            return true;
        }

            @Override
            public boolean onResourceReady(Bitmap resource, Object model, Target < Bitmap > target, DataSource dataSource, boolean isFirstResource) {
                view.setScaleType(scaleType);
                return false;
            }
        };
    }
}